package com.example.concurrent;

import com.example.feignApi.Client;
import lombok.extern.slf4j.Slf4j;
import org.apache.coyote.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author houyangfan
 * @version 1.0
 * @date 2022/7/12 10:28
 */
@RestController
@RequestMapping("/timeout")
@Slf4j
public class TimeOutBug {

    @Autowired
    private Client client;
    /**
     * 超时参数设置分为连接超时和读取超时，对于读取超时，类似 Tomcat 的 Web 服务器都是把服务端请求提交到线程池处理的，
     * 只要服务端收到了请求，网络层面的超时和断开便不会影响服务端的执行。所以读取超时的话，服务端的超时报错下边的代码还是会执行的
     * @param request
     * @param url
     * @param connectTimeout
     * @param readTimeout
     * @return
     */
    public String getResponse(HttpRequest request, String url, int connectTimeout, int readTimeout) {

        return null;
    }

    @GetMapping("client")
    public String client(HttpRequest request) throws IOException {
        log.info("client1 called");
        //服务端5s超时，客户端读取超时2秒
        return getResponse(request,"/server?timeout=5000", 1000, 2000);
    }

    @GetMapping("server")
    public void server(@RequestParam("timeout") int timeout) throws InterruptedException {

        log.info("server called");
        TimeUnit.MILLISECONDS.sleep(timeout);
        log.info("Done");
    }

    @GetMapping("client2")
    public void timeout() {

        long begin=System.currentTimeMillis();
        try{
            client.server();
        }catch (Exception ex){
            log.warn("执行耗时：{}ms 错误：{}", System.currentTimeMillis() - begin, ex.getMessage());
        }
    }

}
